package com.db.bankapp.domain;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.ForkJoinPool;

public class EmailService {
    private final static ExecutorService executor = new ForkJoinPool();
    private final Queue<Email> emails = new BlockingQueue<>();
    private volatile boolean stopped;

    public EmailService() {
        executor.submit(() -> {
            while (!(stopped && emails.isEmpty())) {
                try {
                    if (emails.isEmpty()) {
                        synchronized (emails) {
                            while (emails.isEmpty()) {
                                emails.wait();
                            }
                        }
                    }
                    Email email = emails.remove();
                    sendMail(email);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                    return;
                }
            }
        });
    }

    public void sendNotificationEmail(Email email) {
        if (stopped) {
            throw new IllegalStateException("Service has been stopped");
        }
        synchronized (emails) {
            try {
                emails.add(email);
            } catch (InterruptedException e) {
                // ignore
            }
            emails.notify();
        }
    }

    public boolean isStopped() {
        return stopped;
    }

    public void sendMail(Email email) {
        try {
            Thread.sleep(1000);
            System.out.println("Email " + email + " is sent");
        } catch (InterruptedException e) {
            System.err.println("Email notification " + email + " failed");
        }
    }

    public void close() {
        stopped = true;
    }
}
